package com.bw.redis.controller;


import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.redis.domain.SysDictionary;
import com.bw.redis.domain.SysDictionaryContent;

import com.bw.redis.service.SysDictionaryContentService;
import com.bw.redis.service.SysDictionaryService;
import com.bw.redis.service.SysTypeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/mydictionary")
public class MyRedisController {
    @Autowired
    private SysTypeService sysTypeService;

    @Autowired
    private RedisService redisService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SysDictionaryService dictionaryService;
    @Autowired
    private SysDictionaryContentService dictionaryContentService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 字典表列表
     * @return
     */
    @RequestMapping("/list")
    public R list(Integer current, Integer size){
        PageHelper.startPage(current,size);
        List<SysDictionary> list = null;
        if(redisTemplate.hasKey("dictionaryList")){
            List dictionaryList = redisTemplate.opsForList().range("dictionaryList", 0, -1);

            return R.ok(new PageInfo<>(dictionaryList));
        }
        list = dictionaryService.list();
        redisTemplate.opsForList().leftPushAll("dictionaryList",list);
        String pattern = "cdict*";
        Set<String> keys = redisTemplate.keys(pattern);
        if(keys.isEmpty()){
            getdictye(list);
        }
        return R.ok(new PageInfo<>(list));
    }

    /***
     * chushihua
     * @param result
     */

    private void getdictye(List<SysDictionary> result) {
//
//        List<SysDictionary> result = list.stream()
//                .map(jsonObject -> JSON.toJavaObject(jsonObject, SysDictionary.class))
//                .collect(Collectors.toList());

        List<Integer> idList = result.stream()
                .map(SysDictionary::getId) // 映射SysDictionary到其id字段
                .collect(Collectors.toList()); // 收集所有的id到一个列表中

        Set<Integer> idSet = new HashSet<>(idList);
        System.out.println("---------"+idSet);
        Map<Integer, List<SysDictionaryContent>> filteredMap = new HashMap<>();
        for (Integer id : idSet) {
            List<SysDictionaryContent> sysDictionaryContents = dictionaryContentService.list();
            // 使用流来过滤sysDictionaryContents列表，只保留getDictId等于当前id的对象
            List<SysDictionaryContent> filteredList = sysDictionaryContents.stream()
                    .filter(content -> id.equals(content.getDictId())) // 使用id.equals(...)而不是idSet.contains(...)
                    .collect(Collectors.toList());

            // 如果需要，您可以在这里将filteredList推送到Redis
             redisTemplate.opsForList().leftPushAll("cdict" + id+"", filteredList);
        }


    }


    /**
     * 字典表shuju查询
     * @return
     */
    @RequestMapping("/getByDid")
    public R getByDid(String did){
        List<SysDictionaryContent> list =null;
        if(redisTemplate.hasKey("cdict"+did)){
            list = redisTemplate.opsForList().range("cdict" + did, 0, -1);
            return R.ok(list);
        }
        LambdaQueryWrapper<SysDictionaryContent> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDictionaryContent::getDictId,did);
        list=dictionaryContentService.list(wrapper);
        System.out.println("----------------0"+list);
        redisTemplate.opsForList().leftPushAll("cdict" + did+"", list);
        return R.ok(list);
    }

    /**
     * 字典数据添加
     * @param dictionaryContent
     * @return
     */
    @RequestMapping("/saveDictionary")
    public AjaxResult saveDictionary(@RequestBody SysDictionaryContent dictionaryContent){
        if(redisService.hasKey("cdict"+dictionaryContent.getDictId())){
            redisService.deleteObject("cdict"+dictionaryContent.getDictId());
        }
        boolean save = dictionaryContentService.save(dictionaryContent);
        Message<String> message = MessageBuilder.withPayload(JSONObject.toJSONString(dictionaryContent)).build();
        rocketMQTemplate.syncSend("ddd",message,1500,1);
        return save?AjaxResult.success():AjaxResult.error();
    }

    /**
     * 字典数据删除
     * @param dictId
     * @param id
     * @return
     */
    @RequestMapping("/deteleDictionary")
    public AjaxResult deteleDictionary(Integer dictId,Integer id){
        if(redisService.hasKey("cdict"+dictId)){
            redisService.deleteObject("cdict"+dictId);
        }
        boolean save = dictionaryContentService.removeById(id);
        Message<String> message = MessageBuilder.withPayload(JSONUtil.toJsonStr(dictId)).build();
        rocketMQTemplate.syncSend("xxx",message,1500,1);
        return save?AjaxResult.success():AjaxResult.error();
    }


    /**
     * 字典类型添加修改
     * @param
     * @return
     */
    @RequestMapping("/saveDictionaryC")
    public AjaxResult saveDictionaryC(@RequestBody SysDictionary sysDictionary){
        if(redisService.hasKey("dictionaryList")){
            redisService.deleteObject("dictionaryList");
        }
        boolean save = dictionaryService.saveOrUpdate(sysDictionary);
        Message<String> message = MessageBuilder.withPayload("延时消息").build();
        rocketMQTemplate.syncSend("xxx",message,1500,1);
        return save?AjaxResult.success():AjaxResult.error();
    }
    /**
     * 字典类型添加删除
     */
    @RequestMapping("/deleteDictionaryC")
    public R deleteDictionaryC(Integer id){
        if(redisService.hasKey("dictionaryList")){
            redisService.deleteObject("dictionaryList");
        }
        boolean save = dictionaryService.removeById(id);
        Message<String> message = MessageBuilder.withPayload("延时消息").build();
        rocketMQTemplate.syncSend("xxx",message,1500,1);
        return save?R.ok():R.fail("删除失败");
    }


}
